package com.tim.third.demo.printer.ysy;

import cn.hutool.core.map.MapBuilder;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.*;

/**
 * 
 * @author 
 *
 */
public class PrinterUtil {
	/**
	 * 获取签名
	 * 
	 * @param dayinji
	 * @return
	 */
	public static String getSign(Printer dayinji) {
		String sign = "appid" + dayinji.getAppid()
		            + "deviceid" + dayinji.getDeviceid()
		            + "devicesecret"+ dayinji.getDevicesecret()
		            + "printdata" + dayinji.getData() 
		            + "timestamp" + dayinji.getTimestamp()
			     	+ dayinji.getAppsecret();
		sign = MD5Utils.encodeToHex(sign);
		return sign;
	}

	public static String getReqBody(String key, String val){
		Map<String, String> map = MapBuilder.<String, String>create()
				.put("appid", "10156")
//				.put("appsecret", "ebf5c4559f9710d852c5b77352c4501e")
				.put("deviceid", "70005737")
				.put("devicesecret", "6mbf8ydh")
				.put("timestamp", System.currentTimeMillis()/1000+"")
				.build();
		if(StringUtils.isNotBlank(key)){
			map.put(key, val);
		}
		
		List<String> fields = new ArrayList<>(map.keySet());
		Collections.sort(fields, Comparator.naturalOrder());
		StringBuilder builder = new StringBuilder();
		for(String field : fields){
			if("sign".equals(field)){
				continue;
			}
			String fieldVal = map.get(field);
			builder.append(field).append(fieldVal);
		}
		builder.append(Printer.APP_SECRET);
		String sign = MD5.create()
				.digestHex(builder.toString());//.toUpperCase();
		map.put("sign", sign);
//		System.out.println(sign);
		String jsonStr = JSONUtil.formatJsonStr(JSON.toJSONString(map));
		System.out.println(jsonStr);

		return jsonStr;
	}
/**
 * 发送数据转码
 * @param s
 * @return
 */
	public static String percentEncode(String s) {
	    if (s == null) {
	        return "";
	    }
	    try {
	        return URLEncoder.encode(s, "UTF-8")
	                // OAuth encodes some characters differently:
	                .replace("*", "%2A")
	                .replace("%7E", "~");
	        // This could be done faster with more hand-crafted code.
	    } catch (UnsupportedEncodingException wow) {
	        throw new RuntimeException(wow.getMessage(), wow);
	    }
	}
/**
 * 	发送post
 * @param url 请求url
 * @param datas 请求数据
 * @return
 * @throws ClientProtocolException
 * @throws IOException
 */
public static boolean sendPost(String url,String datas) throws ClientProtocolException, IOException {
	boolean flag = false;
	CloseableHttpClient httpClient = HttpClients.createDefault();
	HttpPost post = new HttpPost(url);//构建post请求
	post.setHeader("Content-type","application/json");//设置请求头
    // 构建消息实体
    StringEntity entity = new StringEntity(datas, Charset.forName("UTF-8"));
    //entity.setContentType("application/x-www-form-urlencoded");//设置请求头
    entity.setContentEncoding("UTF-8");
    post.setEntity(entity);
	CloseableHttpResponse response = httpClient.execute(post);//发送
	if(response.getStatusLine().getStatusCode() == 200) {//请求成功
		if(entity !=null) {
			String str = EntityUtils.toString(response.getEntity());
			System.out.println(str);
	      	JSONObject json = JSONObject.parseObject(str);//解析返回的数据
	      	//String retMsg = json.getString("retMsg");//获取返回的retMsg
	      	System.out.println("errMsg："+json.getString("errMsg"));
	      	flag = true;
		}
	}else {
		System.err.println("请求失败");
	}
	return flag;
}
}
